import { getInfo } from '@/api/user'
import { clearCookie, setCookie, getCookie, removeCookie } from '@/utils/auth'
import { edgeReadFile, edgeListSiddhiApps, edgeGetCode, edgeWrite } from '@/api/siddhi'
import Vue from 'vue'
import { base64EncodeUnicode, base64DecodeUnicode } from "@/utils/utils";
import { streamKey } from '@/utils/local'
import {
    listSiddhiApps,
} from "@/api/siddhi";
import _ from 'lodash'
const state = {
    appConfig: { name: 'avic-iot', description: '', isDirty: false },
    application: {},
    config: {},
    treeList: [], //工作空间 tree
    ediEdgeTabs: [], //页签集合
    activeTab: { name: '', isDirty: false, description: '', isPlay: null },
    treeData: [],
    logObj: [],
    tabList: [],
    listSiddhiApps: [],
    consoleOpen: false,
    drawerShow: false //抽屉的开关建议放在vuex里边(目前改动太大 先放着)
}
var scalarArrayEquals = function (array1, array2) {

    if (!array1 && !array2) {
        return false
    }
    array1 = array1 && array1.filter(item => item)
    array2 = array1 && array2.filter(item => item)
    return array1.length == array2.length && array1.every(function (v, i) { return v.type === array2[i].type && v.name === array2[i].name });
}
const mutations = {
    setListSiddhi(state, data) {
        state.listSiddhiApps = data
    },
    setDel(state, data) {
        // 设置上下节点的删除字段
        let { type, id } = data
        if (!streamKey.includes(type)) {
            if (type.indexOf('.') != -1) {
                type = type.split('.')
                state.activeTab.appData[type[0]][type[1]].forEach(item => {
                    if (item.id == id) {
                        Vue.set(item, 'isDel', true)
                    }
                })
            } else {
                state.activeTab.appData[type].forEach(item => {
                    if (item.id == id) {
                        Vue.set(item, 'isDel', true)
                    }
                })
            }
        }



    },
    //修改抽屉状态
    SET_DRAWER_SHOW: (state) => {
        state.drawerShow = !state.drawerShow
    },
    RESET_APPCONFIG: (state, app) => {
        state.appConfig.name = ''
        state.appConfig.description = ''
    },
    SET_APPCONFIG: (state, appSetting) => {
        state.appConfig.name = appSetting.name
        state.appConfig.description = appSetting.description
    },
    SET_CONFIGURATION(state, configuration) {
        state.config = configuration
    },
    SET_APPLICATION(state, application) {
        state.application = application
    },
    ADD_TAB(state, data) {
        let editTab = state.ediEdgeTabs.find(tab => tab.name == data.name)
        if (editTab == null) {
            state.ediEdgeTabs.push(data)
        } else {
            editTab.actived = true
            state.ediEdgeTabs.filter(tab => tab.actived == true && tab.name != data.name).forEach(actTab => {
                actTab.actived = false
            })
        }
    },
    // 从新赋值json和大tab
    SET_JSON_TAB(state) {
        state.activeTab.appData.siddhiAppName = state.activeTab.name
        // state.activeTab.isSave = true
        const obj = {
            siddhiAppConfig: state.activeTab.appData,
            edgeList: []
        }
        Vue.set(state.activeTab, 'siddhiJson', base64EncodeUnicode(JSON.stringify(obj)))
        // 顺便修改大的tab
        state.ediEdgeTabs.forEach(item => {
            if (item.id == state.activeTab.id) {
                Vue.set(item, 'appData', state.activeTab.appData)
                Vue.set(item, 'name', state.activeTab.name)
                Vue.set(item, 'title', state.activeTab.name)
                Vue.set(item, 'isDirty', state.activeTab.isDirty)
                Vue.set(item, 'isSave', state.activeTab.isSave)
                Vue.set(item, 'description', state.activeTab.description)
                Vue.set(item, 'mxJson', state.activeTab.mxJson)
            }
        })
        console.log('最终的提交===', state.activeTab, state.ediEdgeTabs)
    },
    // 删除
    REM_ACTIVE_TAB(state, data) {
        let { type, id } = data
        let appData = []
        // 一种正常的一种是queryLists下的对象
        if (type.indexOf(".") != -1) {
            type = type.split(".");
            appData = state.activeTab.appData[type[0]][type[1]]
        } else {
            appData = state.activeTab.appData[type]
        }
        // 修改选中的tab
        const index = appData.findIndex(item => item.id == id)
        // 不存在添加-存在替换
        if (index !== -1) {
            appData.splice(index, 1)
        }

        this.commit('siddhi/SET_JSON_TAB')
        this.commit('siddhi/SET_IS_SAVE', true)

    },
    SET_IS_SAVE(state, data = true) {
        state.activeTab.isSave = data
    },
    SET_ACTIVE_TAB_DARA(state, data) {
        const { relateCellData, returnAppConfig } = data
        const { keyType, type, nodeData, nodeDataRight } = returnAppConfig
        let appData = []
        // 一种正常的一种是queryLists下的对象
        if (type == 'queryLists') {
            appData = state.activeTab.appData[type][keyType]
        } else {
            appData = state.activeTab.appData[type]
        }
        // 设置上下节点红色 (判断是否修改过当前节点,如果没有修改,上下节点不添加红色告警)
        // 此处判断了当前节点的name和属性是否被修改过 (且只有!streamKey.includes(type)的需要上下节点红色告警)
        if (streamKey.includes(type) && nodeData.name != nodeDataRight.name || !scalarArrayEquals(nodeDataRight.attributeList, nodeData.attributeList)) {
            const { sourceCell, targetCell } = relateCellData
            if (sourceCell) {
                if (_.isArray(sourceCell)) {
                    sourceCell.forEach(item => {
                        this.commit('siddhi/setDel', item)
                    })
                } else {
                    this.commit('siddhi/setDel', sourceCell)
                }

            }
            if (targetCell) {
                if (_.isArray(targetCell)) {
                    targetCell.forEach(item => {
                        this.commit('siddhi/setDel', item)
                    })
                } else {
                    this.commit('siddhi/setDel', targetCell)
                }
            }
        }

        // 修改选中的tab
        const index = appData.findIndex(item => item.id == nodeData.id)

        // return
        // 不存在添加-存在替换
        if (index === -1) {
            appData.push(nodeData)
        } else {
            console.log(nodeData, '对比======>', appData[index])
            appData[index] = nodeData
        }
        this.commit('siddhi/SET_IS_SAVE', true)
        this.commit('siddhi/SET_JSON_TAB')
    },
    SET_ACTIVE_TAB(state, data) {
        state.activeTab = data

        this.commit('siddhi/SET_JSON_TAB')
    },
    setTabData(state, data) {
        state.ediEdgeTabs.forEach(item => {
            if (item.id == data.id) {
                Vue.set(item, 'appData', data.appData)
            }
        })

    },
    setTableName(state, data) {

        for (let i = 0; i < state.ediEdgeTabs.length; i++) {
            let item = state.ediEdgeTabs[i]
            if (item.id == data.id) {
                Vue.set(item, 'name', data.name)
                Vue.set(item, 'title', data.title)
                Vue.set(item, 'isDirty', data.isDirty)
                Vue.set(item, 'description', data.description)
                Vue.set(item, 'mxJson', data.mxJson)
            }
        }
    },
    // ADD_TAB(state, data) {
    //     state.ediEdgeTabs.push(data)
    // },
    SET_ACTIVE_TAB_JSON(state, data) {
        state.activeTab.siddhiJson = data.siddhiJson;
        state.activeTab.appData = data.appData;
    },
    REMOVE_TAB(state, data) {
        state.ediEdgeTabs.splice(state.ediEdgeTabs.findIndex(tab => tab.name === data.name), 1)
    },
    REMOVE_ALLTAB(state, data) {
        state.ediEdgeTabs = []
    },
    REMOVE_ACTIVE_TAB(state, data) {
        state.activeTab = {}
    },
    SET_TREE_DATA(state, data) {
        // 过滤掉
        // data.forEach(item => {
        //     item.children = item.children.filter(f => f.siddhiAppName != '')
        // })
        state.treeData = data
    },
    SET_LOG_DATA(state, data) {
        state.logObj.push(data)
        var div = document.getElementById("dataList");
        div.scrollTop = div.scrollHeight;
    },
    CLEAR_LOG_DATA(state, data) {
        state.logObj = []
    },
    SET_CONSOLE_OPEN(state, data) {
        state.consoleOpen = data
    },
    setTab(state, data) {
        // const index = state.ediEdgeTabs.findIndex(item => item.id == data.id)
        // if (index == -1) {
        //     state.ediEdgeTabs.push(data)
        // } else {
        //     state.ediEdgeTabs[index] = data
        // }

    }
}
const getters = {
    // 获取流
    getsiddhiFlow: state => {
        return function (val) {
            return state.listSiddhiApps.find(
                (item) => item.siddhiAppName == val
            ).mode;
        }
    },
    // 获取是否有没保存的
    getIsServe: state => {
        return state.ediEdgeTabs.some(
            (item) => item.isSave
        );
    },
    // 校验节点是否有isDel 有代表当前节点的上下节点被修改了
    validateIsDel: state => {
        const key = Object.keys(state.activeTab.appData)
        let flg = true
        const arr = []
        for (let i = 0; i < key.length; i++) {
            const item = key[i];
            if (_.isArray(state.activeTab.appData[item])) {
                state.activeTab.appData[item].forEach(i => {
                    arr.push(i)
                })
            } else if (_.isObject(state.activeTab.appData[item])) {
                const queryKey = Object.keys(state.activeTab.appData[item])
                for (let q = 0; q < queryKey.length; q++) {
                    const query = queryKey[q];
                    state.activeTab.appData[item][query].forEach(o => {
                        arr.push(o)
                    })
                    // arr = arr.concat(state.activeTab.appData[item][query])
                }
            }

        }

        let isDel = arr.filter(f => {
            return f.isDel
        })
        // if (isDel.length === 0) {
        //     flg = true
        // } else {
        //     flg = false
        //     isDel = isDel.map(m => m.name || m.title || m.queryName)
        //     console.log('isDelisDel', isDel)
        //     Vue.prototype.$msg(`请完善${isDel.join(',')}节点信息`)
        // }
        return isDel
    },
    // 节点名称重复校验
    streamKeyIsRepear: state => {
        return (data) => {
            let { id, val } = data
            let isrepeat = false;
            for (let i = 0; i < streamKey.length; i++) {
                const item = streamKey[i];
                isrepeat = state.activeTab.appData[item].some((ele) => {
                    return ele.name == val && ele.id !== id;
                });
                if (isrepeat) {
                    break;
                }
            }
            return isrepeat
        }
    },
    // 获取上下节点 节点type id
    getCell: state => {
        return (data) => {
            let { type, id } = data
            let appData = []
            // 一种正常的一种是queryLists下的对象
            if (type.indexOf(".") != -1) {
                type = type.split(".");
                appData = state.activeTab.appData[type[0]][type[1]]
            } else {
                appData = state.activeTab.appData[type]
            }
            return appData.find(item => item.id == id)
        }
    },
}
const actions = {
    // async getTab({ commit }, filePath) {
    //     let file = await edgeReadFile(filePath);
    //     let currentTabForFile = this.application.tabController.getTabForFile(file);
    //     if (!_.isNil(currentTabForFile)) {
    //         this.application.tabController.setActiveTab(currentTabForFile);
    //         return;
    //     }
    //     let siddhiJson = await this._serviceClient.getDesignMXContent(file.content);
    //     let configurationJSON = base64DecodeUnicode(siddhiJson);
    //     if (configurationJSON != undefined && configurationJSON != '') {

    //         let tempObj = JSON.parse(configurationJSON)
    //         this.initialiseSiddhiAppData(tempObj)
    //         var jsonStr = { content: siddhiJson }
    //         var mxJson = await this._serviceClient.getDesignMXView(jsonStr);
    //         let option = { tabOptions: { file: file } }
    //         _.set(option, 'application', this.application);
    //         _.set(option, 'title', file.name.replace(".siddhi", ""));
    //         _.set(option, 'name', file.name.replace(".siddhi", ""));
    //         _.set(option, 'siddhiJson', siddhiJson);
    //         _.set(option, 'state', 'old');
    //         _.set(option, 'id', generateId());
    //         _.set(option, 'mxJson', mxJson);
    //         _.set(option, 'appData', this.appData);
    //         commit('setTab', option)
    //         // 添加到vuex

    //     }
    // },
    // user login
    setAppconfig({ commit }, appSetting) {
        commit('SET_APPCONFIG', appSetting)
    },
    setConfiguration({ commit }, configuation) {
        commit('SET_CONFIGURATION', configuation)
    },
    setApplication({ commit }, application) {
        commit('SET_APPLICATION', application)
    },
    addTab({ commit }, tab) {
        commit('ADD_TAB', tab)
    },
    setActiveTab({ commit }, tab) {
        commit('SET_ACTIVE_TAB', tab)
    },
    setJson({ commit }, tab) {
        commit('SET_ACTIVE_TAB_JSON', tab)
    },

    removeTab({ commit }, tab) {
        commit('REMOVE_TAB', tab)
    },
    removeAllTab({ commit }, delAlltab) {
        commit('REMOVE_ALLTAB', delAlltab)
    },
    setTreeData({ commit }, treeData) {
        commit('SET_TREE_DATA', treeData)
    },
    setLogData({ commit }, logData) {
        commit('SET_LOG_DATA', logData)
    },
    setConsoleState({ commit }, logData) {
        commit('SET_CONSOLE_OPEN', logData)
    },
    getListSiddhi({ commit }) {
        return new Promise(async (resolve, reject) => {
            const res = await listSiddhiApps();
            const { data } = res;
            commit('setListSiddhi', data)
            resolve(data)
        });
    },
    writeSiddhi({ commit, state }, data) {

        return new Promise(async (resolve, reject) => {
            const cloneData = _.cloneDeep(data)
            if (cloneData) {
                // 修改名称
                commit("SET_ACTIVE_TAB", {
                    ...state.activeTab,
                    name: cloneData.name,
                    title: cloneData.name,
                    // isDirty: true,
                    isSave: false, //保存之后取消指示点
                    // description: cloneData.description,
                    state: "old",
                });
            }

            // 同时更新tab
            // commit("setTableName", that.activeTab);
            await edgeGetCode(state.activeTab.siddhiJson)
                .then((res) => {
                    //根据json格式 获取到code的加密内容 然后写入siddhi
                    var codeBase64 = res.data; //
                    //var dd=base64DecodeUnicode(res.data);//解码
                    var fileNameBase64 = base64EncodeUnicode(
                        state.activeTab.name + '.siddhi'
                    );
                    var workspace64 = base64EncodeUnicode("workspace");
                    var param =
                        "location=" +
                        workspace64 +
                        "&configName=" +
                        fileNameBase64 +
                        "&config=" +
                        codeBase64;
                    //调用写入接口
                    edgeWrite(param)
                        .then((res) => {
                            commit("SET_LOG_DATA", {
                                message: "【" + state.activeTab.name + "】保存成功!",
                                type: "INFO",
                            });
                            commit("SET_CONSOLE_OPEN", true);
                            this.dispatch('siddhi/loadWorkspaceTree')
                            resolve(true)
                        })
                        .catch((Error) => {
                            //console.log(Error.response.data);//抓取控制台日志
                            if (Error.response != undefined) {
                                commit("SET_LOG_DATA", {
                                    message:
                                        "【" +
                                        currentfileName +
                                        "】保存失败!" +
                                        Error.response.data,
                                    type: "ERROR",
                                });
                                commit("SET_CONSOLE_OPEN", true);
                            }
                            resolve(false)
                        });
                })
                .catch((Error) => {
                    Vue.$msg('有错误的数据!');
                    console.log(Error);
                });

        });
    },
    loadWorkspaceTree({ commit }) {
        return new Promise(async (resolve, reject) => {
            try {
                const res = await edgeListSiddhiApps({
                    // envVar: 'e30='
                    path: base64EncodeUnicode('workspace'),
                    id: '#'
                })
                if (res.status == 200) {
                    let treeList = []
                    let item = { mode: '0', siddhiAppName: '工作空间' }
                    res.data = res.data.map(item2 => {
                        return {
                            ...item2,
                            siddhiAppName: item2.text.indexOf('.siddhi') != -1 && _.replace(item2.text, '.siddhi', ''),
                            mode: item2.type,
                        }
                    })

                    let temp1 = _.cloneDeep(res.data)
                    treeList.push(Object.assign(item, { 'children': temp1 }))
                    commit('SET_TREE_DATA', treeList)
                    resolve(treeList)
                }
            } catch (error) {
                if (error.response != undefined) {
                    commit('SET_LOG_DATA', { message: Error.response.data, type: 'ERROR' })
                    commit("SET_CONSOLE_OPEN", true);
                }
            }



        });
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}